package tsing.javase.thread.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

/**
 * @Author Tsing/吴清平
 * @Date 2022/12/28 9:18
 * @Version 1.0
 * 通过自定义线程工厂，创建线程，并做全局异常处理
 *
 */
public class ThreadExceptionDemo {
    private static final Logger log = LoggerFactory.getLogger(ThreadExceptionDemo.class);

    public static void main(String[] args) {




        ExecutorService exc = Executors.newFixedThreadPool(2,new MyThreadFactory());

        exc.execute(new Runnable() {
            @Override
            public void run() {

                int i = 3;
                System.out.println("thread run");
                System.out.println(i / 0);


            }
        });

        exc.execute(new ExceptionHandler());

        exc.shutdown();

    }


}



//自定义线程工厂
class MyThreadFactory implements ThreadFactory{

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        System.out.println(this+" creating new Thread:"+thread.getId());
        thread.setUncaughtExceptionHandler(new MycaughtExcetpionHander()); //设置异常处理
        return thread;
    }
}


/**
 *  全局异常处理
 */

class MycaughtExcetpionHander implements  Thread.UncaughtExceptionHandler{
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        // 捕获，记录异常
        System.out.println("caught "+e);

    }
}




class ExceptionHandler implements  Runnable{

    @Override
    public void run() {
        Thread thread = Thread.currentThread();
        System.out.println("run by" + thread);
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        throw new  RuntimeException();
    }
}
